<template>
  <div>
    <custom-dialog v-model:visible="isShowDialog">
      <div class="dialog-content">
        <div class="title">{{ actionType === 'add' ? '新增存物' : '修改存物' }}</div>
      </div>
      <div class="form-box">
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">物品名称</span>
          <el-input v-model.trim="form.item_name" clearable></el-input>
        </div>
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">物品数量</span>
          <el-input v-model.trim="form.num" clearable></el-input>
        </div>
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">物主姓名</span>
          <el-input v-model.trim="form.user_name" clearable></el-input>
        </div>
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">联系电话</span>
          <el-input type="number" v-model.trim="form.mobile" clearable></el-input>
        </div>
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">存物密码</span>
          <el-input type="password" v-model.trim="form.password" clearable></el-input>
        </div>
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">存物时限</span>
          <el-input
            type="number"
            :min="1"
            placeholder="存物时限（分钟）"
            v-model.trim="form.keep_time"
            clearable
          ></el-input>
        </div>
        <div class="form-item">
          <span class="symbol">*</span>
          <span class="form-title">存放位置</span>
          <el-input type="text" v-model.trim="form.location" clearable></el-input>
        </div>
        <div class="form-item">
          <span class="form-title">备注</span>
          <el-input
            class="textarea-input"
            type="textarea"
            :rows="4"
            placeholder="请输入备注"
            v-model="form.remark"
            clearable
          ></el-input>
        </div>
        <div class="form-item-img">
          <span class="form-title">物品图片</span>
          <el-upload
            class="avatar-uploader"
            :action="baseUrl + 'upload/image'"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            accept="image/jpg,image/jpeg,image/png,image/gif"
            name="iFile"
            :headers="headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="avatar-uploader-icon"><el-icon :size="24"><Plus /></el-icon></i>
          </el-upload>
        </div>
      </div>
      <div class="receive-bottom-btn">
        <div class="cancel-btn" @click="onCancel">取消</div>
        <div class="confirm-btn" @click="onConfirm">确定</div>
      </div>
    </custom-dialog>
  </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { LocalStorage } from '@/utils/storage'
import { userStorageAdd, userStorageDetail, userStorageEdit } from '@/api/userStorage'
import { formTestFun, checkPhoneNumber } from '@/utils/toolsValidate'
import { Plus } from '@element-plus/icons-vue'
import CustomDialog from '@/components/CustomDialog/Index.vue'

const props = defineProps({
  storageVisible: { type: Boolean, default: false },
  actionType: { type: String, default: 'add' },
  detailId: { type: String, default: '' }
})
const emit = defineEmits(['update:storageVisible', 'onConfirm'])

const isShowDialog = computed({
  get: () => props.storageVisible,
  set: val => emit('update:storageVisible', val)
})

const form = reactive({
  item_name: null,
  num: null,
  user_name: null,
  mobile: null,
  password: null,
  keep_time: null,
  location: null,
  image_id: null,
  remark: null
})

const imageUrl = ref('')
const baseUrl = import.meta.env.VITE_API_BASE_URL  
const headers = { 'Access-Token': LocalStorage.get('token') }

function init() {
  form.item_name = null
  form.num = null
  form.user_name = null
  form.mobile = null
  form.password = null
  form.keep_time = null
  form.location = null
  form.image_id = null
  form.remark = null
  imageUrl.value = ''
}

function onCancel() {
  emit('update:storageVisible', false)
}

function onConfirm() {
  const testForm = {
    请输入物品名称: form.item_name,
    请输入物品数量: form.num,
    请输入物主姓名: form.user_name,
    请输入联系电话: form.mobile,
    请输入正确的手机号码: checkPhoneNumber(form.mobile),
    请输入存物密码: form.password,
    请输入存物时限: form.keep_time,
    请输入密码: form.location,
    请输入存放位置: form.location
  }
  if (formTestFun(testForm)) return
  if (props.actionType === 'edit') {
    const payload = { ...form, storage_id: props.detailId }
    userStorageEdit(payload).then(res => {
      if (res.status === 200) {
        ElMessage.success('修改成功')
        emit('update:storageVisible', false)
        emit('onConfirm')
      }
    })
    return
  }
  userStorageAdd(form).then(res => {
    if (res.status === 200) {
      ElMessage.success('操作成功')
      emit('update:storageVisible', false)
      emit('onConfirm')
    }
  })
}

function handleUploadSuccess(res, file) {
  if (res.status === 200) {
    imageUrl.value = res.data.fileInfo.external_url
    form.image_id = res.data.fileInfo.file_id
  }
}

function beforeUpload(file) {
  const img = file.name.substring(file.name.lastIndexOf('.') + 1)
  if (!['jpg', 'png', 'jpeg', 'gif'].includes(img)) {
    ElMessage.error('只能上传图片！')
    return false
  }
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传头像图片大小不能超过 10MB!')
  }
  return isLt10M
}

function getUserStorageDetail() {
  userStorageDetail({ storage_id: props.detailId }).then(res => {
    if (res.status === 200 && res?.data?.detail) {
      Object.entries(res.data.detail).forEach(([key1, value]) => {
        if (Object.prototype.hasOwnProperty.call(form, key1)) {
          form[key1] = value
        }
      })
      imageUrl.value = res.data.detail?.image?.external_url
    }
  })
}

watch(
  () => isShowDialog.value,
  val => {
    if (val) {
      init()
      if (props.actionType === 'edit') {
        getUserStorageDetail()
      }
    }
  }
)
</script>

<style lang="scss" scoped>
::v-deep {
  .el-input__inner {
    border-radius: 12px;
  }
  .el-input {
    width: 200px;
    height: 48px;
  }
}

.avatar-uploader {
  border: 1px dashed #999999;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.dialog-content {
  .title {
    font-size: 20px;
    font-family: PingFang SC, PingFang SC-Bold;
    font-weight: 700;
    text-align: left;
    color: #000000;
    margin-bottom: 10px;
  }
}
.form-box {
  margin-top: 30px;
  display: flex;
  flex-wrap: wrap;
  width: 55vw;
  box-sizing: border-box;
  .form-item {
    display: flex;
    margin-right: 50px;
    align-items: flex-start;
    margin-bottom: 20px;
    .symbol {
      font-size: 18px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #7c0a03;
    }
    .form-title {
      font-size: 18px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #000000;
      margin-right: 20px;
    }
    .textarea-input {
      width: 500px;
    }
  }
  .form-item-img {
    width: 100%;
    display: flex;
    align-items: center;

    .symbol {
      font-size: 18px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #7c0a03;
    }
    .form-title {
      font-size: 18px;
      font-family: PingFang SC, PingFang SC-Regular;
      font-weight: 400;
      color: #000000;
      margin-right: 20px;
    }
  }
}
.receive-bottom-btn {
  margin-top: 30px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 52px;
  .cancel-btn {
    width: 134px;
    height: 52px;
    line-height: 52px;
    background: #ffffff;
    border: 1px solid #333333;
    border-radius: 12px;
    font-size: 18px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #333333;
    cursor: pointer;
  }
  .confirm-btn {
    width: 132px;
    height: 52px;
    background: #7c0a03;
    line-height: 52px;
    border-radius: 12px;
    font-size: 18px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #ffffff;
    margin-left: 40px;
    cursor: pointer;
  }
}
</style>
